Follow Along Links


Posted by wayne201299 on 2023-10-03

DEMO

highlight所有的link

實作

  1. 在HTML添加highlight element

     const triggers = document.querySelectorAll("a");
     const highlight = document.createElement("span");
    
     highlight.classList.add("highlight");
     document.body.appendChild(highlight);
    
  2. 監聽所有連結的mouseenter事件

     triggers.forEach((trigger) => {
         trigger.addEventListener("mouseenter", highlightLink);
     });
    
  3. highlight目前移到的物件上

     function highlightLink() {
         const linkCoords = this.getBoundingClientRect();
         const coords = {
             width: linkCoords.width,
             height: linkCoords.height,
             left: linkCoords.left + window.scrollX,
             top: linkCoords.top + window.scrollY,
         };
    
         highlight.style.width = coords.width + "px";
         highlight.style.height = coords.height + "px";
         highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
     }
    

知識點

  • getBoundingClientRect可以獲得element的相對位置
  • 在 CSS 中,translate 函数是用來移動元素的,它可以在水平和垂直方向上進行平移操作。translate 函数接受兩個參數,分別是水平和垂直方向上的偏移值。這兩個值可以是像素(px)、百分比(%)或其他支持的長度單位。

#javascript







Related Posts

DAY28:Sum of the first nth term of Series

DAY28:Sum of the first nth term of Series

簡明程式解題入門 - 陣列篇 I

簡明程式解題入門 - 陣列篇 I

DAY22:Categorize New Member

DAY22:Categorize New Member


Comments